<template>
  <div>
    <el-form ref="formData" :model="formData" label-width="80px" :rules="formRules">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="formData.nickname" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="formData.mobile" />
      </el-form-item>
      <el-form-item label="角色">
        <el-select v-model="formData.roles" multiple class="width-full">
          <el-option v-for="role in roles" :key="role.id" :label="role.name" :value="role.id" />
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    formId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      dialogLoading: false,
      formData: {
        id: '',
        username: '',
        nickname: '',
        email: '',
        mobile: '',
        remarks: '',
        roles: []
      },
      roles: [],
      formRules: {
        username: [
          { required: true, message: '请输入用户名' }
        ]
      }
    }
  },
  mounted() {
    this.getFormData()
  },
  methods: {
    getFormData() {
      this.getRoles()
      if (this.formId) {
        this.$api.user.find(this.formId).then(res => {
          this.formData = res.data
        })
      }
    },
    getRoles() {
      this.$api.role.listAll().then(res => {
        this.roles = res.data
      })
    },
    submitForm() {
      this.$refs.formData.validate(valid => {
        if (valid) {
          if (!this.formData.id) {
            this.$api.user.save(this.formData).then(res => {
              this.$emit('submitSuccess')
            })
          } else {
            this.$api.user.update(this.formData).then(res => {
              this.$emit('submitSuccess')
            })
          }
        }
      })
    }
  }
}

</script>
<style scoped>
</style>
